package com.weifly.weistock.core.config;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 配置服务基类
 *
 * @author weifly
 * @since 2020/11/30
 */
public class AbstractConfigService {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    protected String configPath; // 存储路径

    /**
     * 设置配置文件路径
     */
    public void setConfigPath(String configPath) {
        this.configPath = configPath;
    }

    protected File getConfigFolder() {
        File configFolder = new File(this.configPath);
        if (!configFolder.exists()) {
            configFolder.mkdirs();
            log.info("创建目录: " + configFolder.getAbsolutePath());
        }
        return configFolder;
    }

    protected Element createEle(DocumentFactory factory, String elementName, Object text) {
        Element ele = factory.createElement(elementName);
        if (text != null) {
            ele.setText(text.toString());
        }
        return ele;
    }

    protected Double getDoubleAttr(Element ele, String attr) {
        String value = ele.attributeValue(attr);
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return Double.valueOf(value);
    }

    protected void saveConfig(File configFile, Document document) {
        try (FileOutputStream output = new FileOutputStream(configFile)) {
            OutputFormat format = new OutputFormat("  ", true, "UTF8");
            XMLWriter writer = new XMLWriter(output, format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
